﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using System.Data.OleDb;
using System.IO;
using System.Transactions;

public partial class Admin_Components_PurchaseOrder_PurchaseOrderCreate : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Username"] != null)
            {
                ResetForm();
            }
        }
    }
    private void ResetForm()
    {
        try
        {
            //Utils.loadShopToCombo(cbShop, 0, 0,"W");
            //Utils.loadShopToComboSearch(cbShopSearch, 1,0,"W");
            Utils.loadVendorToCombo(cbVendor, 0);
            loadProvince();
            rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToDateSearch.SelectedDate = DateTime.Now.Date;
            rdpPurchaseDate.SelectedDate = DateTime.Now.Date;
            txtPurchaseOrderCode.Text = GernerateCode();
            txtStatus.Text = "";
            txtQuantity.Text = "";
            txtPurchasePrice.Text = "";
            txtLastUpdatedBy.Text = Session["Username"].ToString();
            txtLastUpdatedDateTime.Text = DateTime.Now.ToString("dd/MM/yyyy");
            gvProduct.DataSource = new DataTable();
            gvProduct.DataBind();
            //Button
            btnCancel.Enabled = false;
            btnInput.Enabled = false;
            btnAdd.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = true;
            //Combo
            cbShop.Enabled = true;
            cbVendor.Enabled = true;
            cbType.Enabled = true;

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-loadForm:" + ex.Message);
        }
    }
    private void resetGrid()
    {
        ViewState["TBLPurchaseOrderDetail"] = null;
        divTotalQuantity.InnerText = "Tổng số lượng: 0";
        divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
        divGetTotalQuantity.InnerText = "";
        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
        divGetTotalAmount.InnerText = "";
        gvProduct.DataSource = new DataTable();
        gvProduct.DataBind();
        txtQuantity.Text = "";
    }
    private void loadProvince()
    {
        try
        {
            //Load tinh thanh 
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
            Utils.loadLocation(cbProvince, 0, isProvinceAll, ProvinceID);//Tao moi
            Utils.loadLocationSearch(cbProvinceSearch, 0, isProvinceAll, ProvinceID);//Search
            loadShop(ProvinceID, ProvinceID);
            

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-LoadProvince:" + ex.Message);
        }
    }
    private void loadShop(int ProvinceID = -1, int ProvinceIDSearch = -1)
    {
        try
        {
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cbShop, isShopAll, ProvinceID, ShopID, "W");
            Utils.loadShopByProvinceToComboSearch(cbShopSearch, isShopAll, ProvinceIDSearch, ShopID, "W");
            
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-loadShop:" + ex.Message);
        }
    }
    private void SetStatus(string strStatus)
    {
        if (strStatus == "C" || strStatus == "I")//Da nhap kho
        {
            //Button
            //btnCancel.Enabled = false;
            btnInput.Enabled = false;
            btnAdd.Enabled = false;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
            btnCancel.Enabled = false;
            btnImport.Enabled = false;
            cbProvince.Enabled = false;

            //Combo
            cbShop.Enabled = false;
            cbVendor.Enabled = false;
            cbType.Enabled = false;
            gvProduct.Enabled = false;
        }
        if (strStatus == "N")
        {// Tao moi 
            btnCancel.Enabled = true;
            btnInput.Enabled = true;
            btnAdd.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = true;
            btnImport.Enabled = true;
            //Combo
            cbShop.Enabled = false;
            cbVendor.Enabled = false;
            cbType.Enabled = false;
            cbProvince.Enabled = false;
        }
        
    }
    private void loadData(ProPurchaseOrder pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramPurchaseOrderID = helper.Parameter;
            paramPurchaseOrderID.ParameterName = "PurchaseOrderID";
            paramPurchaseOrderID.DbType = DbType.Int32;
            paramPurchaseOrderID.Value = -1;
            helper.AddParameter(paramPurchaseOrderID);
           
            System.Data.Common.DbParameter paramShopID = helper.Parameter;
            paramShopID.ParameterName = "ShopID";
            paramShopID.DbType = DbType.Int32;
            paramShopID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(paramShopID);

            System.Data.Common.DbParameter paramCode = helper.Parameter;
            paramCode.ParameterName = "PurchaseOrderCode";
            paramCode.DbType = DbType.String;
            paramCode.Value = pro.strPurchaseOrderCodeSearch;
            helper.AddParameter(paramCode);

            System.Data.Common.DbParameter ProvinceID = helper.Parameter;
            ProvinceID.ParameterName = "ProvinceID";
            ProvinceID.DbType = DbType.Int32;
            ProvinceID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(ProvinceID);

            System.Data.Common.DbParameter paramStatus = helper.Parameter;
            paramStatus.ParameterName = "Status";
            paramStatus.DbType = DbType.String;
            paramStatus.Value = pro.strStatusSearch;
            helper.AddParameter(paramStatus);
            

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetPurchaseOrder", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}",dt.Rows[0]["TotalRows"]);
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-loadData:" + ex.Message);
        }
    }
    private void fillData(ProPurchaseOrder pro)
    {
        try
        {
            txtPurchaseOrderCode.Text = pro.strPurchaseOrderCode;
            cbShop.SelectedValue = pro.iShopID.ToString();
            cbVendor.SelectedValue = pro.iVendorID.ToString();
            cbType.SelectedValue = pro.strType;
            rdpPurchaseDate.SelectedDate = pro.dateTimePurchaseDate;
            txtStatus.Text = pro.strStatusName;
            txtRemark.Text = pro.strRemark;
            txtLastUpdatedBy.Text = pro.LastUpdatedBy;
            txtLastUpdatedDateTime.Text = pro.LastUpdatedDateTime;
            if (ViewState["PurchaseOrderID"] != null)
            {
                DataTable dt = DTPurchaseOrDetail(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                if (dt.Rows.Count > 0)
                {
                    ViewState["TBLPurchaseOrderDetail"] = dt;
                    Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                    divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                    divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                    divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                    Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                    divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                    divGetTotalAmount.InnerText = iTotalAmount.ToString();

                }
                else
                {
                    divTotalQuantity.InnerText = "Tổng số lượng: 0";
                    divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                    divGetTotalQuantity.InnerText = "";
                    divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                    divGetTotalAmount.InnerText = "";
                }
                if (pro.strType == "P")
                    divTotalWeight.Visible = false;
                gvProduct.DataSource = dt;
                gvProduct.DataBind();
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
            }
            loadProduct();
            SetStatus(pro.strStatus);
            divStamp.Visible = false;

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-fillData:" + ex.Message);
        }
    }
    private void getDataSearch()
    {
        ProPurchaseOrder pro = new ProPurchaseOrder();
        pro.strPurchaseOrderCodeSearch = Utils.KillChars(txtPurchaseCodeSearch.Text.Trim());
        pro.strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        pro.iShopIDSearch = Convert.ToInt32(Utils.KillChars(cbShopSearch.SelectedValue.Trim().ToString() == "" ? "-1" : cbShopSearch.SelectedValue.Trim().ToString()));
        pro.iProvinceIDSearch = Convert.ToInt32(Utils.KillChars(cbProvinceSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbProvinceSearch.SelectedValue.Trim().ToString()));
        pro.strStatusSearch = Utils.KillChars(cbStatusSearch.SelectedValue.Trim().ToString());
        pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));

        loadData(pro);
    }
    private bool save(ProPurchaseOrder pro)
    {
        db = new DBDataContext();
        db.Connection.Open();
        try
        {
            #region Tao moi
            if (ViewState["PurchaseOrderID"] == null)//Insert INTO PurChaseOrder
            {
                using (var transation = new TransactionScope())
                {
                    try
                    {
                        string strPurchaseOrderCode = GernerateCode();
                        PurchaseOrder obj = new PurchaseOrder();

                        obj.PurchaseOrderCode = Utils.KillChars(strPurchaseOrderCode);
                        obj.OrderNumber = Convert.ToInt32(Utils.KillChars(strPurchaseOrderCode.Substring(2, strPurchaseOrderCode.Length - 2)));
                        obj.PurchaseDate = Convert.ToDateTime(Utils.KillChars(rdpPurchaseDate.SelectedDate.ToString()));
                        obj.ShopID = pro.iShopID;
                        obj.VendorID = pro.iVendorID;
                        obj.TotalQuantity = pro.iTotalQuantity;
                        obj.TotalAmount = pro.dTotalAmount;
                        obj.CreatedBy = Session["Username"].ToString();
                        obj.CreatedDateTime = DateTime.Now;
                        obj.LastUpdatedBy = Session["Username"].ToString();
                        obj.LastUpdatedDateTime = DateTime.Now;
                        obj.ProductType = pro.strType;
                        obj.Remark = pro.strRemark;
                        obj.Status = Convert.ToChar(pro.strStatus);
                        //db.PurchaseOrders.InsertOnSubmit(obj);
                        //ViewState["PurchaseOrderID"] = obj.ID;
                        db.Insert<PurchaseOrder>(obj);
                        db.SubmitChanges();

                        ViewState["PurchaseOrderID"] = obj.ID;
                        //Insert PurchaseOrderDetail
                        db.Insert<PurchaseOrderDetail>(insertPurchaseOrderDetail(Convert.ToInt32(ViewState["PurchaseOrderID"])));
                        db.SubmitChanges();
                        transation.Complete();

                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("PurchaseOrder Page-Save-Transation-Status-N:" + ex.Message);
                        transation.Dispose();
                        ViewState["PurchaseOrderID"] = null;
                        return false;
                    }
                }
            }
            #endregion End Tao moi
            else
            {   //UPDATE PurchaseOrder
                string strUserName = Session["Username"].ToString();
                PurchaseOrder obj = db.PurchaseOrders.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["PurchaseOrderID"]));
                obj.PurchaseDate = Convert.ToDateTime(Utils.KillChars(rdpPurchaseDate.SelectedDate.ToString()));
                //obj.ShopID = Convert.ToInt32(Utils.KillChars(cbShop.SelectedValue.ToString()));
                obj.Remark = pro.strRemark;
                obj.TotalAmount = pro.dTotalAmount;
                obj.TotalQuantity = pro.iTotalQuantity;
                obj.LastUpdatedBy = strUserName;
                obj.LastUpdatedDateTime = DateTime.Now;
                obj.Status = Convert.ToChar('C');
                db.SubmitChanges();
                /**
                * Update hoac Insert vao Tồn Kho: Warehouse
                * Nếu ProductID đã tồn tại thì Update lại tồn kho
                * Nếu ProductID chưa thì Insert vào
                * Price Product update không phân biệt Shop
                * Update  lai gia mua PurchasePrice = (PurchasePrice + OldPurchasePrice)/2 
                * */

                //List<Warehouse> listWarehouse = new List<Warehouse>();
                #region Nhap kho
                if (pro.strStatus == "C")//Tinh trang Nhập kho
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            //Delete du lieu cu
                            deletePurchaseOrderDetail(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                            //Insert lai moi
                            db.Insert<PurchaseOrderDetail>(insertPurchaseOrderDetail(Convert.ToInt32(ViewState["PurchaseOrderID"])));
                            //obj.Status = Convert.ToChar(pro.strStatus);
                            db.SubmitChanges();
                            int iProductID = 0;
                            int iPackType = 0;
                            int? iShopID = obj.ShopID;
                            
                            int? iQuantity = 0;
                            double? dPurchasePrice = 0;
                            var listDetail = (from a in db.PurchaseOrderDetails where a.Status == 'A' && a.PurchaseOrderID == Convert.ToInt32(ViewState["PurchaseOrderID"]) select a).ToList();
                            List<StampWarehouse> listStampWarehouseInsert = new List<StampWarehouse>();
                            List<StampWarehouse> listStampWarehouseUpdate = new List<StampWarehouse>();
                            List<Warehouse> listWarehouseInsert = new List<Warehouse>();
                            List<Warehouse> listWarehouseUpdate = new List<Warehouse>();

                            foreach (var a in listDetail)
                            //foreach (GridDataItem item in gvProduct.Items)
                            {
                                //iProductID = Convert.ToInt32(Utils.KillChars(item["ProductID"].Text.Trim().ToString()));
                                iProductID = Convert.ToInt32(a.ProductID);
                                iPackType = Convert.ToInt32(a.PackType);
                                iQuantity = a.Quantity;
                                dPurchasePrice = a.PurchasePrice;
                                //Caculate: Quantity
                                var checkExistsProduct = (from c in db.Warehouses
                                                          where c.ProductID == iProductID
                                                                && c.ShopID == iShopID
                                                                && c.PackType == iPackType
                                                                && c.Status == 'A'
                                                          select c).FirstOrDefault();
                                if (checkExistsProduct == null)//ProductID chua ton tai thi Insert Warehouse
                                {
                                    Warehouse objWarehouse = new Warehouse();
                                    objWarehouse.RefCode = obj.PurchaseOrderCode;
                                    objWarehouse.RefType = "Nhập kho tổng";
                                    objWarehouse.Remark = "PurchaseOrder";
                                    objWarehouse.ProductID = iProductID;
                                    objWarehouse.ShopID = iShopID;
                                    objWarehouse.PackType = iPackType;
                                    objWarehouse.PurchasePrice = dPurchasePrice;
                                    objWarehouse.Quantity = iQuantity;
                                    objWarehouse.CreatedBy = strUserName;
                                    objWarehouse.CreatedDateTime = DateTime.Now;
                                    objWarehouse.LastUpdatedBy = strUserName;
                                    objWarehouse.LastUpdatedDateTime = DateTime.Now;
                                    objWarehouse.Status = 'A';
                                    listWarehouseInsert.Add(objWarehouse);
                                    //db.Insert<Warehouse>(objWarehouse);
                                    //db.SubmitChanges();
                                }
                                else //ProductID  ton tai thi Update Quantity, PurchasePrice: Warehouse
                                {
                                    //Caculate: Quantity
                                    checkExistsProduct.Quantity = checkExistsProduct.Quantity + iQuantity;
                                    checkExistsProduct.RefCode = obj.PurchaseOrderCode;
                                    checkExistsProduct.RefType = "Nhập kho tổng";
                                    checkExistsProduct.Remark = "PurchaseOrder";
                                    if (checkExistsProduct.Quantity <= 0)// so luong = 0
                                    {
                                        dPurchasePrice = 0;
                                    }
                                    else
                                    {
                                        double dOldPurchasePrice = Convert.ToDouble(checkExistsProduct.PurchasePrice);
                                        checkExistsProduct.PurchasePrice = dOldPurchasePrice == 0 ? dPurchasePrice : (dOldPurchasePrice + dPurchasePrice) / 2;
                                    }
                                    listWarehouseUpdate.Add(checkExistsProduct);
                                    //db.SubmitChanges();
                                }
                                if (obj.ProductType == "R" && iPackType > 1)// Add List tem ra khoi kho tem
                                {
                                    var stamp = (from c in db.StampWarehouses
                                                 where c.ProductID == iProductID
                                                       && c.Status == 'A'
                                                       && c.PackType == iPackType
                                                 select c).FirstOrDefault();
                                    if (stamp != null)
                                    {
                                        stamp.Quantity = stamp.Quantity - a.Quantity;
                                        listStampWarehouseUpdate.Add(stamp);
                                        //db.SubmitChanges();
                                    }
                                    else
                                    {
                                        StampWarehouse stampWarehouse = new StampWarehouse();
                                        stampWarehouse.ProductID = iProductID;
                                        stampWarehouse.PackType = iPackType;
                                        stampWarehouse.Quantity = (-1) * a.Quantity;
                                        stampWarehouse.CreatedBy = strUserName;
                                        stampWarehouse.LastUpdatedBy = strUserName;
                                        stampWarehouse.CreatedDateTime = DateTime.Now;
                                        stampWarehouse.LastUpdatedDateTime = DateTime.Now;
                                        stampWarehouse.Status = 'A';
                                        //db.Insert<StampWarehouse>(stampWarehouse);
                                        listStampWarehouseInsert.Add(stampWarehouse);
                                    }
                                }
                            }//End select Detail
                            //Tru kho Warehouse
                            if (listWarehouseInsert.Count > 0)
                            {
                                db.Insert<Warehouse>(listWarehouseInsert);
                            }
                            if (listWarehouseUpdate.Count > 0)
                            {
                                db.Update<Warehouse>(listWarehouseUpdate);
                            }
                            //Tru Stamp
                            if (listStampWarehouseInsert.Count > 0)
                            {
                                db.Insert<StampWarehouse>(listStampWarehouseInsert);
                            }
                            if (listStampWarehouseUpdate.Count > 0)
                            {
                                db.Update<StampWarehouse>(listStampWarehouseUpdate);
                            }
                            
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("PurchaseOrder Page-Save-Transation-Status-C-PurchaseOrderID-" + ViewState["PurchaseOrderID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            //ViewState["PurchaseOrderID"] = null;
                            return false;
                        }
                    }//End Transaction
                }
                #endregion End nhap kho
                #region Da Luu
                if (pro.strStatus == "N")
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            //db.SubmitChanges();
                            //Delete du lieu cu
                            deletePurchaseOrderDetail(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                            //Insert lai moi
                            db.Insert<PurchaseOrderDetail>(insertPurchaseOrderDetail(Convert.ToInt32(ViewState["PurchaseOrderID"])));
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("PurchaseOrder Page-Save-Transation-Status-N-PurchaseOrderID-" + ViewState["PurchaseOrderID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            //ViewState["PurchaseOrderID"] = null;
                            return false;
                        }
                    }
                }
                #endregion End Da luu
            }//End cap nhat

            db.Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-Save:" + ex.Message);
            db.Connection.Close();
            return false;
        }
        finally
        {
            db.Connection.Close();
        }
    }
    private void delete(int ID)
    {
        db = new DBDataContext();
        db.Connection.Open();
        PurchaseOrder obj = db.PurchaseOrders.FirstOrDefault(x => x.ID == ID);
        obj.LastUpdatedDateTime = DateTime.Now;
        obj.LastUpdatedBy = Session["Username"].ToString();
        obj.Status = 'I';

        db.Update<PurchaseOrder>(obj);
        db.SubmitChanges();
        db.Connection.Close();

    }
    private string GernerateCode()
    {
        string strCode = string.Empty;
        try
        {
            //Fortmat: NH00000001
            /*
         
              int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
                int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
                String LastCode = ("000000" + MaxOrderNumber).ToString();
                String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
             */
            
            db = new DBDataContext();
            //PurchaseOrder obj = new PurchaseOrder();


            var PurchaseOrderMax = db.PurchaseOrders.Max(d => d.OrderNumber);
            int MaxOrderNumber = (PurchaseOrderMax == null ? 0 : Convert.ToInt32(PurchaseOrderMax)) + 1;
            String strLastCode = "00000000" + MaxOrderNumber.ToString();
            strCode = "NH" + strLastCode.Substring(strLastCode.Length - 8);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-GernerateCode:" + ex.Message);
            ResetForm();
        }
        return strCode;
    }
    private DataTable createTable()
    {
        DataTable dt = null;
        try
        {
            if (ViewState["TBLPurchaseOrderDetail"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.String"));
                dt.Columns.Add("PackType", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("PurchasePrice", System.Type.GetType("System.Double"));
                dt.Columns.Add("Quantity", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));
                //dt.Columns.Add("Delete");
            }
            else dt = (DataTable)ViewState["TBLPurchaseOrderDetail"];
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-createTable:" + ex.Message.ToString());
        }
        return dt;
    }
    private void addDataToTable(ProPurchaseOrder pro)
    {
        try
        {
            DataTable dt = createTable();
            //check ma san pham da chon chua, neu đa ton tai thi update

            DataRow[] rowArr = dt.Select("ProductID='" + pro.ProductID + "'");// Fortmar: ProductID | PackType
            if (rowArr.Count() > 0)
            {
                //string[] arr = cbProduct.SelectedValue.ToString().Split('|');
                //DataRow row = rowArr[0];
                //row["PurchasePrice"] = Utils.KillChars(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //int iQuantity = Convert.ToInt32(row["Quantity"]) + Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
                //row["Quantity"] = iQuantity;
                //row["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
                //Double iAmount = iQuantity * Convert.ToDouble(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //row["Amount"] = iAmount;
                DataRow row = rowArr[0];
                row.Delete();
                dt.AcceptChanges();
            }

            DataRow drNew = dt.NewRow();
            string[] arr = pro.ProductID .Split('|');

            drNew["ProductID"] = pro.ProductID;
            drNew["PackType"] = arr[1];
            drNew["ProductName"] = pro.ProductName;
            drNew["PurchasePrice"] = Utils.KillChars(pro.PurchasePrice.Trim().Replace(",", ""));
            int iQuantity = Convert.ToInt32(Utils.KillChars(pro.Quantity.Trim().Replace(",", "")));
            drNew["Quantity"] = iQuantity;
            drNew["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
            Double iAmount = Convert.ToDouble(pro.Quantity.Trim().Replace(",", "")) * Convert.ToDouble(pro.PurchasePrice.Trim().Replace(",", ""));
            drNew["Amount"] = iAmount;
            dt.Rows.Add(drNew);

            ViewState["TBLPurchaseOrderDetail"] = dt;
            if (dt.Rows.Count > 0)
            {
                Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                divTotalQuantity.InnerText = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                divTotalAmount.InnerText = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                divGetTotalAmount.InnerText = iTotalAmount.ToString();
            }
            else
            {
                divTotalQuantity.InnerText = "Tổng số lượng: 0";
                divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                divGetTotalQuantity.InnerText = "";
                divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                divGetTotalAmount.InnerText = "";
            }
            if (arr[1] == "0")
                divTotalWeight.Visible = false;
            gvProduct.DataSource = dt;
            gvProduct.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate-addDataToTable:" + ex.Message.ToString());
        }
    }
    private string StampQuantityRemain(int iPurchaseOrderID = 0)
    {
        string strResult = string.Empty;
        try
        {
            db = new DBDataContext();
            db.Connection.Open();
            var list = (from a in db.PurchaseOrderDetails
                        //join b in db.Products on a.ProductID equals b.ID
                        join b in db.StampWarehouses on new { a.ProductID, a.PackType } equals new { b.ProductID, b.PackType }
                        join c in db.Products on a.ProductID equals c.ID
                        where a.PurchaseOrderID == iPurchaseOrderID && a.Status == 'A' && b.Status == 'A' && b.Quantity < 0 && c.ProductType == "R"
                        select new
                        {
                            ProductName = c.ProductCode + "-" + c.ProductName + " (" + a.PackType + " Kg) = " + Convert.ToString(b.Quantity),
                            QuantityRemain = b.Quantity
                        }).ToList();

            if (list.Count > 0)
            {
                strResult = "<B><I><U>Số lượng tem tồn kho theo sản phẩm:</I></U> ";
                foreach (var p in list)
                {
                    if (p.QuantityRemain < 0)
                    {
                        strResult = strResult + "<BR/>&nbsp;&nbsp;- &nbsp;" + p.ProductName;
                    }
                }
                strResult = strResult + "</B>";
            }

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreatePurchaseOrder Page-getStamp:" + ex.Message.ToString());
        }
        finally {
            db.Connection.Close();
        }
        return  strResult;
    }
    private DataTable DTPurchaseOrDetail(int iPurchaseOrderID = 0)
    {
        //DataTable dt = null;
        try
        {
            db = new DBDataContext();
            db.Connection.Open();
            var dtPurchaseOrderDetail = (from a in db.PurchaseOrderDetails
                                         join b in db.Products on a.ProductID equals b.ID
                                         where a.PurchaseOrderID == iPurchaseOrderID && a.Status == 'A' && b.Status == 'A'
                                         select new
                                         {
                                             ProductID = b.ID + "|" + a.PackType,
                                             ProductName = b.ProductCode +"-" + b.ProductName + (a.PackType == 0 ? "" : " (" + a.PackType + " Kg)"),
                                             PackType = a.PackType,
                                             PurchasePrice = Convert.ToDouble(a.PurchasePrice),
                                             Amount = Convert.ToDouble(a.Amount),
                                             Quantity = a.Quantity,
                                             Weight = a.PackType * a.Quantity
                                         }).ToList();


            return dtPurchaseOrderDetail.ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-DTPurchaseOrDetail:" + ex.Message.ToString());
            return new DataTable();
        }
        finally
        { 
            db.Connection.Close();
        }   
        
    }
    private void deletePurchaseOrderDetail(int iPurchaseOrderID = 0)
    {
        db = new DBDataContext();
        //db.Connection.Open();
        try
        {
            if (iPurchaseOrderID != 0)
            {

                List<PurchaseOrderDetail> soDetail = (from sd in db.PurchaseOrderDetails where sd.PurchaseOrderID == iPurchaseOrderID select sd).ToList<PurchaseOrderDetail>();
                db.Delete<PurchaseOrderDetail>(soDetail);
                db.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-deletePurchaseOrderDetail:" + ex.Message.ToString());
        }
        //finally
        //{
        //    db.Connection.Close();
        //}
    }
    private List<PurchaseOrderDetail> insertPurchaseOrderDetail(int iPurchaseOrderID = 0)
    {
        try
        {
            List<PurchaseOrderDetail> listPurchaseOrderDetail = new List<PurchaseOrderDetail>();
            foreach (GridDataItem item in gvProduct.Items)
            {
                string[] arr = Utils.KillChars(item["ProductID"].Text.Trim()).Split('|');
                PurchaseOrderDetail soDetail = new PurchaseOrderDetail();
                soDetail.PurchaseOrderID = iPurchaseOrderID;
                soDetail.ProductID = Convert.ToInt32(arr[0]);
                soDetail.PackType = Convert.ToInt32(arr[1]);//PackType
                string strPurchasePrice = Utils.KillChars(((Label)(item.FindControl("lblPurchasePrice"))).Text.Trim().Replace(",", ""));
                soDetail.PurchasePrice = Convert.ToDouble(strPurchasePrice == "" ? "0" : strPurchasePrice);
                string strQuantity = Utils.KillChars(((Label)(item.FindControl("lblQuantity"))).Text.Trim().Replace(",", ""));
                soDetail.Quantity = Convert.ToInt32(strQuantity == "" ? "0" : strQuantity);
                string strAmount = Utils.KillChars(((Label)(item.FindControl("lblAmount"))).Text.Trim().Replace(",", ""));
                soDetail.Amount = Convert.ToDouble(strAmount == "" ? "0" : strAmount);
                soDetail.CreatedBy = Session["UserName"].ToString();
                soDetail.LastUpdatedBy = Session["UserName"].ToString();
                soDetail.CreatedDateTime = DateTime.Now;
                soDetail.LastUpdatedDateTime = DateTime.Now;
                soDetail.Status = 'A';
                listPurchaseOrderDetail.Add(soDetail);
            }
            return listPurchaseOrderDetail;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-insertPurchaseOrderDetail:" + ex.Message);
            return null;
        }
        
    } 
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["Username"] != null)
            {
                ProPurchaseOrder pro = new ProPurchaseOrder();
                pro.iShopID = Convert.ToInt32(Utils.KillChars(cbShop.SelectedValue.ToString() == "" ? "0" : cbShop.SelectedValue.ToString()));
                pro.iVendorID = Convert.ToInt32(Utils.KillChars(cbVendor.SelectedValue.ToString()) == "" ? "0" : Utils.KillChars(cbVendor.SelectedValue.ToString()));
                pro.strType = Utils.KillChars(cbType.SelectedValue.ToString());
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.strStatus = "N";

                #region Validate Input
                if (String.IsNullOrWhiteSpace(rdpPurchaseDate.SelectedDate.ToString()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn ngày nhập đơn hàng!");
                    rdpPurchaseDate.Focus();
                    return;
                }
                if (String.IsNullOrWhiteSpace(cbShop.SelectedValue))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng!");
                    cbShop.Focus();
                    return;
                }
                if (String.IsNullOrWhiteSpace(pro.strType))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại gạo!");
                    cbType.Focus();
                    return;
                }
                if (gvProduct.Items.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng thêm chi tiết sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                #endregion
                pro.iTotalQuantity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
                pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());

                if (save(pro))
                {
                    txtStatus.Text = "Tạo mới";
                    SetStatus("N");
                    btnSave.Enabled = false;
                    btnAdd.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
                }
                else
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            }  
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreatePurchaseOrder Page-btnSave_Click:" + ex.Message.ToString());
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
        }
    }
    protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        loadProduct();
        resetGrid();
    }
    protected void cbProvince_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (!cbProvince.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvince.SelectedValue.Trim()))
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
        
        if (!cbProvinceSearch.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvinceSearch.SelectedValue.Trim()))
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
        
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                ProPurchaseOrder pro = new ProPurchaseOrder();
                //Insert PurchaseOrderDetail
                if (string.IsNullOrEmpty(cbType.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại gạo!");
                    cbType.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(cbProduct.SelectedValue))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(txtQuantity.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng!");
                    txtQuantity.Focus();
                    return;
                }
                if (txtQuantity.Text.Trim() == "0")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng phải lớn hơn 0!");
                    txtQuantity.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(txtPurchasePrice.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập giá sản phẩm!");
                    txtPurchasePrice.Focus();
                }
                if (txtPurchasePrice.Text.Trim() == "0")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Giá nhập phải lớn hơn 0!");
                    txtPurchasePrice.Focus();
                    return;
                }

                pro.ProductID = cbProduct.SelectedValue.Trim().ToString();
                pro.ProductName = cbProduct.SelectedItem.Text.Trim().ToString();
                pro.PurchasePrice = txtPurchasePrice.Text.Trim();
                pro.Quantity = txtQuantity.Text.Trim();
                addDataToTable(pro);
                if (cbType.SelectedValue == "P")
                    divTotalWeight.Visible = false;
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
                cbProduct.Enabled = true;
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("PurchaseOrderCreate Page-btnAdd_Click:" + ex.Message);
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Thêm không thành công, vui lòng thực hiện lại!");
            }
        }
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                ProPurchaseOrder pro = new ProPurchaseOrder();

                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "PurchaseOrderID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetPurchaseOrder", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            pro.strPurchaseOrderCode = dt.Rows[0]["PurchaseOrderCode"].ToString();
                            pro.iShopID = Convert.ToInt32(dt.Rows[0]["ShopID"].ToString());
                            pro.iVendorID = Convert.ToInt32(dt.Rows[0]["VendorID"].ToString());
                            pro.strType = dt.Rows[0]["ProductType"].ToString();
                            pro.strStatus = dt.Rows[0]["Status"].ToString();
                            pro.dateTimePurchaseDate = Convert.ToDateTime(dt.Rows[0]["PurchaseDate"].ToString());
                            pro.strStatusName = dt.Rows[0]["StatusName"].ToString();
                            pro.dTotalAmount = Convert.ToDouble(dt.Rows[0]["TotalAmount"].ToString());
                            pro.iTotalQuantity = Convert.ToInt32(dt.Rows[0]["TotalQuantity"].ToString());
                            pro.strRemark = dt.Rows[0]["Remark"].ToString();
                            pro.LastUpdatedBy = dt.Rows[0]["LastUpdatedBy"].ToString();
                            pro.LastUpdatedDateTime = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["PurchaseOrderID"] = ID;
                            fillData(pro);

                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("PurchaseOrderCreate Page-gvData_ItemCommand-EditItem-PurchaseOrderID:" +ViewState["PurchaseOrderID"].ToString() + "-" + ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("PurchaseOrder Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("PurchaseOrderCreate Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 2;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void gvProduct_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;
            string strProductID = e.CommandArgument.ToString();//Lay ID 
            if (commandName == "EditItem")
            {
                try
                {
                    DataTable dt = (DataTable)ViewState["TBLPurchaseOrderDetail"];
                    DataRow[] rows = dt.Select("ProductID='" + strProductID + "'");
                    if (rows.Count() > 0)
                    {
                        DataRow row = rows[0];
                        txtPurchasePrice.Text = String.Format("{0:#,#.##}", row["PurchasePrice"]);
                        txtQuantity.Text = String.Format("{0:#,#.##}", row["Quantity"]);
                        cbProduct.SelectedValue = strProductID.ToString();
                        cbProduct.Enabled = false;
                        ViewState["TBLPurchaseOrderDetail"] = dt;
                        div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}", gvProduct.Items.Count);
                        gvProduct.DataSource = dt;
                        gvProduct.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand-EditItem:" + ex.Message);
                }
            }
            else if (commandName == "DeleteItem")
            //if (commandName == "DeleteItem")
            {
                try
                {
                    DataTable dt = (DataTable)ViewState["TBLPurchaseOrderDetail"];
                    //DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                    DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                    if (rowArr.Count() > 0)
                    {
                        //string[] arr = cbProduct.SelectedValue.ToString().Split('|');
                        //DataRow row = rowArr[0];
                        //row["PurchasePrice"] = Utils.KillChars(txtPurchasePrice.Text.Trim().Replace(",", ""));
                        //int iQuantity = Convert.ToInt32(row["Quantity"]) + Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
                        //row["Quantity"] = iQuantity;
                        //row["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
                        //Double iAmount = iQuantity * Convert.ToDouble(txtPurchasePrice.Text.Trim().Replace(",", ""));
                        //row["Amount"] = iAmount;
                        DataRow row = rowArr[0];
                        if (row["PackType"] == "0")
                            divTotalWeight.Visible = false;
                        row.Delete();
                        dt.AcceptChanges();
                    }
                    ViewState["TBLPurchaseOrderDetail"] = dt;
                    if (dt.Rows.Count > 0)
                    {
                        Double iTotalQuantity = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Quantity"])));
                        divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                        divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                        divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                        Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                        divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                        divGetTotalAmount.InnerText = iTotalAmount.ToString();
                    }
                    else
                    {
                        divTotalQuantity.InnerText = "Tổng số lượng: 0";
                        divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                        divGetTotalQuantity.InnerText = "";
                        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                        divGetTotalAmount.InnerText = "";
                    }

                    div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
                    gvProduct.DataSource = dt;
                    gvProduct.DataBind();
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand-DeleteItem:" + ex.Message);
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand:" + ex.Message);
        }
    }
    private void loadProduct()
    {
        if (cbType.SelectedValue == "R")
        {
            Utils.loadProductPurchaseOrder(cbProduct, 0, "R");
        }
        if (cbType.SelectedValue == "P")
        {
            Utils.loadProductPurchaseOrder(cbProduct, 0, "P");
        }
    }
    private DataTable dtListImportExcel(string filePath)
    {
        try
        {
            DataTable dt = new DataTable();
            string connectionString = string.Empty;

            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Server.MapPath(filePath) + "';Extended Properties=Excel 12.0;";
            //if (strFortmat == ".xls")
            //    connectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + Server.MapPath(filePath) + "';Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            string strSQL = "SELECT  * FROM [Sheet1$]";
            OleDbConnection excelConnection = new OleDbConnection(connectionString);
            excelConnection.Open(); // this will open an Excel file
            OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);

            // create data table
            dataAdapter.Fill(dt); 
            // dispose used objects
            //dTable.Dispose();
            dataAdapter.Dispose();
            dbCommand.Dispose();
            excelConnection.Close();
            excelConnection.Dispose();
            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreatePurchaseOrder Page-dtListImportExcel:" + ex.Message.ToString());
            return new DataTable();
            
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void btnInput_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (gvProduct.Items.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chi tiết sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                ProPurchaseOrder pro = new ProPurchaseOrder();
                pro.strStatus = "C";
                pro.iShopID = Convert.ToInt32(Utils.KillChars(cbShop.SelectedValue.ToString() == "" ? "0" : cbShop.SelectedValue.ToString()));
                pro.iTotalQuantity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
                pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                if (save(pro))
                {
                    txtStatus.Text = "Đã nhập kho";
                    SetStatus("C");
                    btnSave.Enabled = false;
                    btnAdd.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Nhập kho thành công!");
                    string strStampRemain = StampQuantityRemain(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                    if (!string.IsNullOrEmpty(strStampRemain))
                    {
                        lblStamRemain.Text = strStampRemain;
                        divStamp.Visible = true;
                    }
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Nhập kho không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("CreatePurchaseOrder Page-btnInput_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Nhập kho không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("/PurchaseOrder", false);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            if (ViewState["PurchaseOrderID"] != null)
            {

                delete(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                SetStatus("I");
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
            }
        }
    }
    #region Properties
    public class ProPurchaseOrder
    {
        public string strPurchaseOrderCode { get; set; }
        public DateTime dateTimePurchaseDate { get; set; }
        public string strRemark { get; set; }
        public string strType { get; set; }
        public string LastUpdatedBy { get; set; }
        public string LastUpdatedDateTime { get; set; } 
        public int?  iShopID { get; set; }
        public string strShopName { get; set; }
        public int? iVendorID { get; set; }
        public int? iOrderNumber { get; set; }
        public string strVendorName { get; set; }
        public string strStatus { get; set; }
        public string strStatusName { get; set; }
        public int? iPurchaseOrderPrice { get; set; }
        public int? iAmount { get; set; }
        public int? iQuantity { get; set; }
        public string PurchasePrice { get; set; }
        public string ProductID { get; set; }
        public string ProductName { get; set; }
        public string Quantity { get; set; } 
        public int? iPackType { get; set; }
        public double? dTotalAmount { get; set; }
        public int? iTotalQuantity { get; set; }
        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strTypeSearch { get; set; }
        public int? iShopIDSearch { get; set; }
        public int? iProvinceIDSearch { get; set; }
        public string strPurchaseOrderCodeSearch { get; set; }
        public string strStatusSearch { get; set; }
    }
    #endregion End Properties

    protected void btnImport_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (string.IsNullOrEmpty(cbType.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại gạo!");
                    cbType.Focus();
                    return;
                }
                if (fuImport.Value.ToString().Equals(""))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn file cần import!");
                    fuImport.Focus();
                    return;
                }
                if (fuImport.Value.ToString().IndexOf(".xlsx") == -1 && fuImport.Value.ToString().IndexOf(".xls") == -1)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "File không hợp lệ. Vui lòng chọn file Excel(.xls, .xlsx)!");
                    fuImport.Focus();
                    return;
                }
                string strFortmat = string.Empty;
                if (fuImport.Value.ToString().IndexOf(".xls") > 0)
                    strFortmat = ".xls";
                if (fuImport.Value.ToString().IndexOf(".xlsx") > 0)
                    strFortmat = ".xlsx";   
                if (!fuImport.Value.ToString().Equals(""))
                {
                    string dirFileServer = Utils.UploadFile(fuImport, Page, "/Admin/Upload/", strFortmat, Session["Username"].ToString());
                    if (!dirFileServer.Equals(""))
                    {
                        DataTable dt = dtListImportExcel(dirFileServer);
                        string strProductCode = string.Empty;
                        string strPackType = string.Empty;
                        string strPrice = string.Empty;
                        string strQuantity = string.Empty;
                        string strType = cbType.SelectedValue;
                        int  checkProduct = 0;
                        int iSTT = 0;
                        
                        if (dt.Columns.Count > 0 && dt.Rows.Count > 0)
                        {
                            db = new DBDataContext();// Validate file Import
                            ProPurchaseOrder pro = new ProPurchaseOrder();
                            #region Validate Data Import
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                // Validate file Import
                                strProductCode = dt.Rows[i][1].ToString();
                                strPackType = dt.Rows[i][3].ToString();
                                strPrice = dt.Rows[i][4].ToString();
                                strQuantity = dt.Rows[i][5].ToString();
                                checkProduct = 0;
                                iSTT += i + 1;
                                if (string.IsNullOrEmpty(strProductCode))
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập mã sản phẩm. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (string.IsNullOrEmpty(strPackType))
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập loại bao gạo. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (!strPackType.Equals("1") &&!strPackType.Equals("10") && !strPackType.Equals("20") && !strPackType.Equals("50"))
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Loại bao gạo không hợp lệ. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (string.IsNullOrEmpty(strPrice))
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập giá. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                int iPrice = 0;
                                bool isNum = int.TryParse(strPrice, out iPrice);
                                if (!isNum)
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Giá nhập không hợp lệ. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (iPrice <= 0)
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Giá nhập phải lớn hơn 0. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (string.IsNullOrEmpty(strQuantity))
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                int iQuantity = 0;
                                isNum = int.TryParse(strQuantity, out iQuantity);
                                if (!isNum)
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng không hợp lệ. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                if (iQuantity <= 0)
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng phải lớn hơn 0. Lỗi tại STT " + iSTT);
                                    return;
                                }
                                //Check sản phẩm đã tồn tại trong hệ thống chưa
                                checkProduct  = (from b in db.Products
                                                 where b.Status == 'A' && b.ProductCode == strProductCode && b.ProductType == strType
                                                   select new {  b.ID }
                                                   ).Count();
                                if (checkProduct <= 0)
                                {
                                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Mã sản phẩm: "+strProductCode+" chưa tồn tại trong hệ thống. Lỗi tại STT " + iSTT);
                                    return;
                                }
                            }
                            #endregion End Validate Data Import
                            #region Insert Data vao Grid
                            //Insert data vao Grid
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                strProductCode = dt.Rows[i][1].ToString();
                                strPackType = dt.Rows[i][3].ToString();
                                strPrice = dt.Rows[i][4].ToString();
                                strQuantity = dt.Rows[i][5].ToString();

                                var getProduct = (from b in db.Products
                                                  where b.Status == 'A' && b.ProductCode == strProductCode && b.ProductType == strType
                                                  select new { b.ID, b.ProductName }
                                                   ).First();

                                pro.ProductID = getProduct.ID + "|" + strPackType;
                                pro.ProductName = strProductCode + "-" + getProduct.ProductName + " (" + strPackType + " Kg)";
                                pro.Quantity = strQuantity;
                                pro.PurchasePrice = strPrice;
                                addDataToTable(pro);
                            }
                            #endregion End Insert Data vao Grid

                            FileInfo theFile = new FileInfo(Server.MapPath(dirFileServer));
                            if (theFile.Exists)//Import thanh cong thi xoa file import
                            {
                                theFile.Delete();
                            }
                        }
                        else
                        {
                            FileInfo theFile = new FileInfo(Server.MapPath(dirFileServer));
                            if (theFile.Exists)//Import thanh cong thi xoa file import
                            {
                                theFile.Delete();
                            }
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Không tìm thấy dữ liệu để import. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
                            return;
                        }
                     

                    }
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("CreatePurchaseOrder Page-btnImport_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Import không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
                return;
            }
        }
    }
    
}